package light.head.controller.el;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.config.ConfigParm;
import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.el.CourseDAO;
import light.head.dao.el.CourseDataDAO;
import light.head.dao.el.TrainDataAnnexDAO;
import light.head.dao.el.TrainDataDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.FileInfo;
import light.head.model.el.CourseDataRelation;
import light.head.model.el.TrainData;
import light.head.model.el.TrainDataAnnex;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(Url.C_DATA)
public class DataController extends SupporterController{
	
	private final static String upload_path = "upload/data/";
	private final static String file_path = "upload/dataimg/";
	private TrainDataDAO dataDAO;
	private TrainDataAnnexDAO taDAO;
	private CourseDAO courseDAO;
	private CourseDataDAO cmrDAO;

	@RequestMapping(Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response){
		return new ModelAndView(Url.DATA_INIT);
	}
	
	@RequestMapping(Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response){
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME, Parm.CC, Parm.DELETED);
		dataDAO.findByMap(cu_organCode(request), map, pb);
		request.setAttribute(Parm.PAGE_BEAN, pb);
		return new ModelAndView(Url.DATA_LIST);
	}
	
	@RequestMapping(Url.EDIT)
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		if(isNotNull(code)){
			TrainData tm = dataDAO.get(Integer.parseInt(code));
			List<TrainDataAnnex> list = taDAO.findByTmc(tm.getCode());
			List<CourseDataRelation> cmrList = cmrDAO.findByTmc(tm.getCode());
			tm.setList(list);
			tm.setCmrList(cmrList);
			request.setAttribute(Parm.TM, tm);
		}
		return new ModelAndView(Url.DATA_EDIT);
	}
	
	@RequestMapping(Url.SAVE)
	@Transactional(rollbackFor = Exception.class)
	public void save(TrainData tm, HttpServletRequest request, HttpServletResponse response) throws Exception{
		RESULT result = RESULT.ERROR;
		if(tm.getCode() == null){//保存
			Date ct = new Date();
			tm.setOc(cu_organCode(request));
			tm.setCu(cu_code(request));
			tm.setCt(ct);
			tm.setDeleted(false);
			if(dataDAO.add(tm) == RESULT.SUCCESS){
				List<CourseDataRelation> cmrList = tm.getCmrList();//保存课程关系
				for(CourseDataRelation cmr : cmrList){
					if(cmr != null && cmr.getCc() != null){
						cmr.setTdc(tm.getCode());
						if(cmrDAO.add(cmr) != RESULT.SUCCESS){
							throw new RuntimeException("操作失败!");
						}
					}
				}
				List<TrainDataAnnex> list = tm.getList();//保存附件
				if(list != null && list.size() > 0){
					for(TrainDataAnnex tda : list){
						tda.setTdc(tm.getCode());
						tda.setDeleted(false);
						if(taDAO.add(tda) != RESULT.SUCCESS){
							throw new RuntimeException("操作失败!");
						}
					}
				}
				result = RESULT.SUCCESS;
			}
		}else{//修改
			if(dataDAO.update(tm) == RESULT.SUCCESS){
				//修改课程关系
				List<CourseDataRelation> oldCmrList = cmrDAO.findByTmc(tm.getCode());
				List<CourseDataRelation> cmrList = tm.getCmrList();
				List<CourseDataRelation> updCmrList = new ArrayList<CourseDataRelation>();
				List<CourseDataRelation> addCmrList = new ArrayList<CourseDataRelation>();
				for(CourseDataRelation cmr : cmrList){
					if(cmr != null && cmr.getCc() != null){
						for(CourseDataRelation oldCmr : oldCmrList){
							if(cmr.getCc().intValue() == oldCmr.getCc().intValue()){
								updCmrList.add(oldCmr);
								addCmrList.add(cmr);
							}
						}
					}
				}
				//增加
				for(CourseDataRelation acmr : addCmrList){
					cmrList.remove(acmr);
				}
				for(CourseDataRelation add : cmrList){
					if(add != null && add.getCc() != null){
						add.setTdc(tm.getCode());
						cmrDAO.add(add);
					}
				}
				//删除
				for(CourseDataRelation remCmr : updCmrList){
					oldCmrList.remove(remCmr);
				}
				cmrDAO.delAll(oldCmrList);
				
				//修改附件
				List<TrainDataAnnex> oldList = taDAO.findByTmc(tm.getCode());
				List<TrainDataAnnex> list = tm.getList();
				List<TrainDataAnnex> updList = new ArrayList<TrainDataAnnex>();
				if(list != null && list.size() > 0){
					for(TrainDataAnnex tma : list){
						if(tma != null && tma.getCode() != null){
							for(TrainDataAnnex old : oldList){
								if(tma.getCode().intValue() == old.getCode().intValue()){
									updList.add(old);
								}
							}
						}
					}
					//删除
					for(TrainDataAnnex t : updList){
						oldList.remove(t);
					}
					for(TrainDataAnnex del : oldList){
						del.setDeleted(true);
						taDAO.upd(del);
					}
					//修改
					for(TrainDataAnnex upd : updList){
						taDAO.upd(upd);
					}
					//增加
					for(TrainDataAnnex add : list){
						System.out.println(add.getCode());
						System.out.println(add.getSn());
						if(add != null && add.getCode() == null && isNotNull(add.getSn())){
							add.setTdc(tm.getCode());
							add.setDeleted(false);
							taDAO.add(add);
						}
					}
				}else{
					if(oldList != null && oldList.size() > 0){
						for(TrainDataAnnex del : oldList){
							del.setDeleted(true);
							taDAO.upd(del);
						}
					}
				}
				result = RESULT.SUCCESS;
			}
		}
		if(RESULT.SUCCESS == result){
			print(response, Msg.SUCCESS);
		}else{
			print(response, Msg.ERROR);
		}
	}
	

	@Transactional
	@RequestMapping(Url.UPLOAD)
	public void uploadFiles(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
		List<MultipartFile> photos = multipartRequest.getFiles("photo");

		StringBuffer result = new StringBuffer("");
		if (null != photos && photos.size() > 0) {
			
			String name = null;
			String ext = null;
			String uuid = null;
			String path = null;
			String savePath = null;
			UUID u = null;
			
			for (MultipartFile mf : photos) {
				name = mf.getOriginalFilename();
				if (isNotNull(name)) {
					ext = name.substring(name.lastIndexOf('.') + 1);
					if (!ext.toUpperCase().equals(Sys.PDF)) {
						result.append("{\"result\":\"file_type_error\"}");
						print(response, result.toString());
						return;
					}
					name = name.substring(0, name.indexOf('.'));
					u = UUID.randomUUID();
					uuid = u.toString().replace("-", "");
					path = upload_path + uuid + Sys.DOT + ext;
					savePath = ConfigParm.getProjectPath() + path;
					FileOutputStream fo;
					int size = 0;
					try {
						fo = new FileOutputStream(savePath);
						size = mf.getBytes().length;
						if(size > 20 * 1024 * 1024){
							result.append("{\"result\":\"file_size_error\"}");
							print(response, result.toString());
							return;
						}
						fo.write(mf.getBytes());
						fo.close();
					} catch (Exception e) {
						print(response, Msg.ERROR);
						e.printStackTrace();
					}

					FileInfo f = new FileInfo();
					f.setDeleted(false);
					f.setExt(ext);
					f.setName(name);
					f.setUuid(uuid);
					f.setCt(new Date());
					f.setType(Sys.B_ONE);
					f.setModule(Parm.TRAINING_MATERIAL);
					f.setCu(cu_code(request));
					f.setOc(cu_organCode(request));
					f.setSize(size);
					dataDAO.add(f);
					result.append("{\"name\":\"" + name + "\",\"code\":\""
							+ f.getCode() + "\",\"ext\":\"" + ext
							+ "\",\"size\":\"" + size + "\",\"path\":\"" + uuid
							+ "\"},");
				}
			}
			result.insert(0, "{\"result\":\"success\",\"list\":[").deleteCharAt(result.length() - 1).append("]}");
			print(response, result.toString());
		} else {
			result.append("{\"result\":\"not_find_file\"}");
			print(response, result.toString());
		}
	}
	@Transactional
	@RequestMapping(Url.UPLOADS)
	public void upload1(HttpServletRequest request, HttpServletResponse response){
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
		MultipartFile pohto = multipartRequest.getFile("upload");
		String type = request.getParameter("t");
		String name = pohto.getOriginalFilename();

		if (isNotNull(name)) {
			String ext = name.substring(name.indexOf('.') + 1);
			if (!ext.toUpperCase().equals(Sys.JPG) 
					&& !ext.toUpperCase().equals(Sys.GIF) && !ext.toUpperCase().equals(Sys.JPEG)
					&& !ext.toUpperCase().equals(Sys.BMP) && !ext.toUpperCase().equals(Sys.PNG)
					&& !ext.toUpperCase().equals(Sys.XLSX) && !ext.toUpperCase().equals(Sys.XLS)
					&& !ext.toUpperCase().equals(Sys.DOCX) && !ext.toUpperCase().equals(Sys.DOC)
					&& !ext.toUpperCase().equals(Sys.PDF) && !ext.toUpperCase().equals(Sys.PPT)
					&& !ext.toUpperCase().equals(Sys.RAR) && !ext.toUpperCase().equals(Sys.ZIP)) {
				print(response,Msg.FILE_TYPE_ERROR);
				return;
			}
			name = name.substring(0, name.indexOf('.'));

			UUID u = UUID.randomUUID();
			String uuid = u.toString().replace("-", "");
			String path = file_path + uuid + Sys.DOT + ext;
			String savePath = ConfigParm.getProjectPath() + path;//request.getSession().getServletContext().getRealPath(path);
			FileOutputStream fo;
			int size = 0;
			
			try {
				fo = new FileOutputStream(savePath);
				size = pohto.getBytes().length;
				fo.write(pohto.getBytes());
				fo.close();
			} catch (Exception e) {
				print(response,Msg.ERROR);
				e.printStackTrace();
			}
			
			FileInfo f = new FileInfo();
			f.setDeleted(false);
			f.setExt(ext);
			f.setName(name);
			f.setUuid(uuid);
			f.setCt(new Date());
			if (type.equals("file"))
				f.setType(Sys.B_ONE);
			else 
				f.setType(Sys.B_TWO);
			f.setModule(Parm.COMMODITY);
			f.setCu(cu_code(request));
			f.setOc(cu_organCode(request));
			f.setSize(size);
			dataDAO.add(f);
			
			StringBuffer result = new StringBuffer();
			result.append("<script type=\"text/javascript\">");
			if (isNotNull(path)) {
				result.append("window.parent.CKEDITOR.tools.callFunction("
		                + request.getParameter("CKEditorFuncNum") + ",'" + path + "',''" + ")");
				result.append("</script>");
				result.append(path);
			} else {
				result.append("alert(\"上传失败，文件类型需要jpg、gif或png\")");
				result.append("</script>");
			}
			response.setHeader("Content-Type", "text/html; charset=UTF-8");
			print(response,result.toString());

		} else {
			print(response,Msg.ERROR);
		}

	}
	
	//选择课程
	@RequestMapping(Url.AID_INIT)
	public ModelAndView aidInit(HttpServletRequest request, HttpServletResponse response){
		return new ModelAndView(Url.DATA_COURSEINIT);
	}
	
	@RequestMapping(Url.AID_LIST)
	public ModelAndView aidList(HttpServletRequest request, HttpServletResponse response){
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, "codes", "cn");
		courseDAO.aidFindByMap(cu_organCode(request), map, pb);
		request.setAttribute(Parm.PAGE_BEAN, pb);
		return new ModelAndView(Url.DATA_COURSELIST);
	}
	
	//屏蔽
	@RequestMapping(Url.SHIELD)
	public void shield(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		RESULT result = RESULT.ERROR;
		if(isNotNull(code)){
			TrainData tm = dataDAO.get(Integer.parseInt(code));
			if(tm != null){
				tm.setDeleted(true);
				result = dataDAO.upd(tm);
			}
		}
		
		if(RESULT.SUCCESS == result){
			print(response, Msg.SUCCESS);
		}else{
			print(response, Msg.ERROR);
		}
	}
	
	//解除屏蔽
	@RequestMapping(Url.UN_SHIELD)
	public void unshield(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		RESULT result = RESULT.ERROR;
		if(isNotNull(code)){
			TrainData tm = dataDAO.get(Integer.parseInt(code));
			if(tm != null){
				tm.setDeleted(false);
				result = dataDAO.upd(tm);
			}
		}
		
		if(RESULT.SUCCESS == result){
			print(response, Msg.SUCCESS);
		}else{
			print(response, Msg.ERROR);
		}
	}
	@Autowired
	public void setDataDAO(TrainDataDAO dataDAO) {
		this.dataDAO = dataDAO;
	}
	@Autowired
	public void setTaDAO(TrainDataAnnexDAO taDAO) {
		this.taDAO = taDAO;
	}
	@Autowired
	public void setCourseDAO(CourseDAO courseDAO) {
		this.courseDAO = courseDAO;
	}
	@Autowired
	public void setCmrDAO(CourseDataDAO cmrDAO) {
		this.cmrDAO = cmrDAO;
	}
	
}
